var express = require('express');
var router = express.Router();

const Quert = require('../utils/db.js')
const timeStamp = require('time-stamp')
const { api_url, verifyToken } = require('../utils//config')
const formidable = require('formidable')
const fs = require('fs')
const path = require('path')
const { v4: uuid } = require('uuid')



router.get('/', async function (req, res, next) {
    res.send('需要token的接口')
});


router.get('/demo', async (req, res, next) => {
    res.send('demo')
})
// 获取视频信息
router.get('/video', async (req, res, next) => {
    let { id = '' } = req.query

    if (id == '') {
        next({
            msg: '请传递必要的参数',
            status: 500
        })
        return
    }

    let sql = `SELECT video_title,CONCAT('http://localhost:3000/uploads/video/',video_src) AS video_src FROM e_video WHERE id=${id}`
    let res1 = await Quert(sql)

    if (res1.result.length > 0) {
        let data = {
            msg: "OK",
            status: 200,
            result: res1.result[0]
        }
        res.send(data)
    } else {
        next({
            msg: '请传递必要的参数',
            status: 500
        })
        return
    }
})

// 报名

router.post('/study', async (req, res, next) => {
    let { cid = '', mid = '' } = req.body
    if (cid == '' || mid == '') {
        next({
            "msg": "请传递必要参数",
            "status": 500
        })
        return
    }

    let sql1 = `SELECT * FROM e_order WHERE cid='${cid}' AND mid='${mid}'`
    let res1 = await Quert(sql1)
    if (res1.result.length > 0) {
        next({
            "msg": "已经报名此课程",
            "status": 500
        })
        return
    }

    let num = (Math.random() + '').substring(2, 8)
    let oid = timeStamp('YYYYMMDDHHmmss') + num
    let createdate = Date.now()

    let sql2 = `INSERT INTO e_order (oid,cid,mid,createdate,status) VALUES ('${oid}','${cid}','${mid}','${createdate}',1)`
    let res2 = await Quert(sql2)
    if (res2.result.affectedRows > 0) {
        res.send({
            "msg": "OK",
            "status": 200
        })

    }
})

// 获取用户
router.get('/user', async (req, res, next) => {

    let { mid } = req.query

    let sql = `SELECT *,CONCAT ('${api_url}','/uploads/head/', head_photo_url) AS head_photo_url FROM e_member WHERE mid='${mid}'`
    let res1 = await Quert(sql)
    delete res1.result[0].password

    if (res1.result.length > 0) {

        let data = {
            msg: "OK",
            status: 200,
            result: res1.result[0]
        }
        res.send(data)
    } else {
        next({
            "msg": "查无此人",
            "status": 500
        })
        return
    }
})

// 更新用户信息
router.put('/user', async (req, res, next) => {

    // let { mid, realname, sex, birthdate, city } = req.body

    // if (mid == '' || realname == '' || sex == '' || birthdate == '') {
    //     next({
    //         "msg": "请传递必要参数",
    //         "status": 500
    //     })
    //     return
    // }

    // let sql = `UPDATE e_member SET realname='${realname}',sex=${sex},birthdate=${birthdate},city='${city}'  WHERE mid='${mid}'`
    // let res1 = await Quert(sql)

    // res.send(res1)
    // return
    // if (res1.result.affectedRows > 0) {
    //     let data = {
    //         "msg": "OK",
    //         "status": 200
    //     }
    //     res.send(data)
    // }

    let { mid = '', realname = '', sex = '', birthdate = '', city = '' } = req.body;

    if (mid == '') {
        next({
            msg: '请传递必要参数',
            status: 500
        })
        return
    }
    let strsql = '';
    if (realname != '') {
        if (strsql == '') {
            strsql += `realname='${realname} '`
        } else {
            strsql += `, realname='${realname} '`;
        }
    }
    if (sex != '') {
        if (strsql == '') {
            strsql += `sex='${sex}'`
        } else {
            strsql += `,sex='${sex} '`
        }
    }
    if (birthdate != '') {
        if (strsql == '') {
            strsql += `birthdate='${birthdate}' `
        } else {
            strsql += `,birthdate='${birthdate}' `
        }
    }
    if (city != '') {
        if (strsql == '') {
            strsql += `city='${city}' `
        } else {
            strsql += `,city='${city}' `
        }
    }
    let sql = `UPDATE e_member SET ${strsql} WHERE mid='${mid}'`
    let res1 = await Quert(sql);


    if (res1.result.affectedRows > 0) {
        let data = {
            msg: 'OK',
            status: 200,
            result: res1.result
        }
        res.send(data)
    }

})

// 获取学习记录
// 通过mid查询order找到cid 查询课程信息返回值
router.get('/orders', async (req, res, next) => {
    let { mid = '' } = req.query;
    if (mid == '') {
        next({
            msg: '请传递正确的用户id',
            status: 500
        })
        return
    }
    let sql = `SELECT oid,title,price,subject_name,area_name,createdate,type,image_src FROM e_order JOIN e_course ON e_order.cid=e_course.cid where mid='${mid}'`

    let res1 = await Quert(sql);
    if (res1.result.length > 0) {
        res.send({
            msg: "OK",
            status: 200,
            result: res1.result
        })
    }

})

// 更新用户头像
router.post('/uploadhead', async (req, res, next) => {
   
    const form = formidable({
        uploadDir: path.join(__dirname, '../temdir') //临时的路径存放地址
    });
    form.parse(req, async (err, fields, files) => {
        //console.log( fields );
        let mid = fields.mid

        //1. 根据原文件名称，生成一个  年月日时分秒 + 随机数
        let filename = files.f.name
        let houzhuiming = path.extname(filename)

        if (!files.f.size) {
            next({
                msg: '请上传一个文件'
            })
            return
        }
        //新文件名称
        let newFileName = timeStamp('YYYYMMDDHHmmss') + (Math.random() + '').substring(2, 8) + houzhuiming
        //2. 移动到uploads文件夹
        //fs.renameSync( 源,新 )
        let sourceFilePath = files.f.path//源路径
        let newFilePath = path.join(__dirname, '../uploads/head', newFileName)//新路径
        fs.renameSync(sourceFilePath, newFilePath)
        //2. 更新数据表中的用户的头像信息 （需要什么参数？用户的mid）
        let sql = `
          UPDATE e_member SET head_photo_url='${newFileName}' WHERE mid='${mid}'
        `
        let [, result] = await Quert(sql)
        if (result.affectedRows > 0) {
            res.send({
                msg: "OK",
                status: 200,
                result: api_url + 'uploads/head/' + newFileName
            })
            return
        }

        next({
            msg: "稍后再试"
        })

    });


})
module.exports = router;
